﻿using ApiLib.Controllers;
using ApiLib.Generator.Common;
using ApiLib.Generator.Tools;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace ApiLib.Generator.Controllers;

/// <summary>
/// 
/// </summary>
[ApiDescriptionSettings(GenConstants.ApiDescriptionSettings)]
public class CommonController : BaseController
{
    /// <summary>
    /// 代码生成swagger.json=>blazor项目请求代码
    /// </summary>
    /// <param name="config"></param>
    /// <returns></returns>
    [AllowAnonymous]
    public FileResult GenSwaggerCode(GenConfig config)
    {
        if (string.IsNullOrEmpty(config.SwaggerJsonUrl))
        {
            var baseUrl = (Request.IsHttps ? "https://" : "http://") + Request.Host;
            config.SwaggerJsonUrl = baseUrl + "/swagger/Default/swagger.json";
        }

        if (string.IsNullOrEmpty(config.ModuleName))
        {
            config.ModuleName = "ServerApi";
        }

        var zipFile = SwaggerGenCodeTool.BuildCodeFile(config);
        return GetFileResult(GetFile(zipFile), "code.zip");
    }
    
    /// <summary>
    /// 数据库结构导出
    /// </summary>
    /// <returns></returns>
    public FileResult GenDbExcel()
    {
        if (DbScope==null)
        {
            throw ActionException("数据库连接异常");
        }
        var memoryStream = DbGenExcelTool.BuildDbExcel(DbScope);
        return GetFileResult(memoryStream, "数据库表.xlsx");
    }
    /// <summary>
    /// 数据库结构导出
    /// </summary>
    /// <returns></returns>
    public FileResult GenDbExcel2()
    {
        if (DbScope==null)
        {
            throw ActionException("数据库连接异常");
        }
        var memoryStream = DbGenExcelTool.BuildDbExcel2(DbScope);
        return GetFileResult(memoryStream, "数据库表.xlsx");
    }
    /// <summary>
    /// 数据库结构导出
    /// </summary>
    /// <returns></returns>
    public FileResult GenDbExcel3()
    {
        if (DbScope==null)
        {
            throw ActionException("数据库连接异常");
        }
        var memoryStream = DbGenExcelTool.BuildDbExcel3(DbScope);
        return GetFileResult(memoryStream, "数据库表.xlsx");
    }
}